class Solution
{
public:
    ListNode* mergeTwoLists(ListNode* list1, ListNode* list2)
    {
        if (list1 == nullptr)
            return list2;
        if (list2 == nullptr)
            return list1;
        ListNode* list = new ListNode;
        ListNode* head = list;
        while (list1 != nullptr && list2 != nullptr)
        {
            if (list1->val >= list2->val)
            {
                list->next = list2;
                list2 = list2->next;
            }
            else
            {
                list->next = list1;
                list1 = list1->next;
            }
            list = list->next;
        }
        if (list1 == nullptr)
            list->next = list2;
        if (list2 == nullptr)
            list->next = list1;
        return head->next;
    }
    ListNode* mergeKLists(vector<ListNode*>& lists, int i, int j)
    {
        int m = j - i;
        if (m == 0) return nullptr;
        if (m == 1) return lists[i];
        ListNode* left = mergeKLists(lists, i, i + m / 2);
        ListNode* right = mergeKLists(lists, i + m / 2, j);
        return mergeTwoLists(left, right);
    }

    ListNode* mergeKLists(vector<ListNode*>& lists)
    {
        return mergeKLists(lists, 0, lists.size());
    }
};